package 练习01_同步查找文件内容;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

/**
 * @ClassName: SearchFileThread
 * @Author: AllenSun
 * @Date: 2022/3/18 上午1:19
 */
public class SearchFileThread implements Runnable {

    private File file;
    private String search;
    public SearchFileThread(File file,String search) {
        this.file=file;
        this.search=search;
    }
    public String readFileContent(File file) {
        try (FileReader fr = new FileReader(file)) {
            char[] all = new char[(int)file.length()];
            fr.read(all);
            return new String(all);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public void run() {
        String fileContent = readFileContent(file);
        if(fileContent.contains(search)){
            System.out.printf("找到子目标字符串%s，在文件：%s%n",search,file);
        }
    }
}
